﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using EntitiesModel;
using IMCModel;



/*
IMCModel.PlatEntities 的成员：Tbl_users 
IMCModel.EadEntitiesModel 的成员:TBL_USER_PRODUCTS,TBL_ACM_SERVICE ,TBL_USER_IP_MAC_INFO,TBL_ACM_USER
DPModel.Entities 的成员：Dp_sys_org_users
 */

namespace ITMan
{
    public partial class FormUser : Form
    {
        public FormUser()
        {
            InitializeComponent();
        }

        public BindingSource bindingSource = new BindingSource();

        private void UserForm_Load(object sender, EventArgs e)
        {
            //dataGridViewUser.ClearSelection();
            //using (var eaddbContext = new EadEntitiesModel())
            //{
            //   var AcmUsers =from u in eaddbContext.TBL_ACM_USERs
            //                    orderby u.USER_ID descending 
            //                    select new {u.PLAT_USER_ID,u.USER_ID,u.FULL_NAME,u.USER_NAME,u.USER_PASSWORD,u.STATUS,u.ONLINE_LIMIT};
            //    bindingSource.DataSource = AcmUsers;
            //    dataGridViewUser.DataSource = bindingSource;
            //    dataGridViewUser.VirtualMode = true;
                
            //    dataGridViewUser.Columns["PLAT_USER_ID"].HeaderText = "平台用户ID";
            //    dataGridViewUser.Columns["USER_ID"].HeaderText = "接入用户ID";
            //    dataGridViewUser.Columns["FULL_NAME"].HeaderText = "姓名";
            //    dataGridViewUser.Columns["USER_NAME"].HeaderText = "登录名";
            //    dataGridViewUser.Columns["USER_PASSWORD"].HeaderText = "密码";
            //    dataGridViewUser.Columns["STATUS"].HeaderText = "状态";
            //    dataGridViewUser.Columns["ONLINE_LIMIT"].HeaderText = "点数";
            //    dataGridViewUser.MultiSelect = true;
            //}
        }

        private void btQuery_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbQuery.Text))
            {
                dataGridViewUser.DataSource = null;
                dataGridViewMac.DataSource = null;
                using (var eaddbContext = new EadEntitiesModel())
                {
                    var AcmUsers = from u in eaddbContext.TBL_ACM_USERs
                                   where u.USER_NAME.Contains(tbQuery.Text) || u.FULL_NAME.Contains(tbQuery.Text)
                                   orderby u.USER_ID descending
                                   select new { u.PLAT_USER_ID, u.USER_ID, u.FULL_NAME, u.USER_NAME, u.STATUS, u.ONLINE_LIMIT };
                    if (AcmUsers.Any())
                    {
                        bindingSource.DataSource = AcmUsers;
                        dataGridViewUser.DataSource = bindingSource;

                        dataGridViewUser.Columns["PLAT_USER_ID"].HeaderText = "平台用户ID";
                        dataGridViewUser.Columns["USER_ID"].HeaderText = "接入用户ID";
                        dataGridViewUser.Columns["FULL_NAME"].HeaderText = "姓名";
                        dataGridViewUser.Columns["USER_NAME"].HeaderText = "登录名";
                        //dataGridViewUser.Columns["USER_PASSWORD"].HeaderText = "密码";
                        dataGridViewUser.Columns["STATUS"].HeaderText = "状态";
                        dataGridViewUser.Columns["ONLINE_LIMIT"].HeaderText = "点数";
                        dataGridViewUser.MultiSelect = true;

                        IQueryable<object> mac = from m in eaddbContext.TBL_USER_IP_MAC_INFOs
                                                 where m.USER_ID == Convert.ToInt32(dataGridViewUser.CurrentRow.Cells["USER_ID"].Value.ToString())
                                                 orderby m.ID descending 
                                                               select new {m.ID,m.USER_ID,m.MAC_ADDRESS};
                        if (mac.Any())
                        {
                            BindingSource macBind = new BindingSource();
                            macBind.DataSource = mac;
                            dataGridViewMac.DataSource = macBind;

                            dataGridViewMac.Columns["ID"].HeaderText = "ID";
                            dataGridViewMac.Columns["USER_ID"].HeaderText = "用户ID";
                            dataGridViewMac.Columns["MAC_ADDRESS"].HeaderText = "Mac地址";
                            dataGridViewMac.Columns["MAC_ADDRESS"].Width = 160;
                        }
                        else
                        {
                            dataGridViewMac.DataSource = null;
                        }
                    }
                    else
                    {
                        dataGridViewUser.DataSource = null;
                        MessageBox.Show(string.Format("未查询到登录名或姓名为\"{0}\"'的用户!", tbQuery.Text));
                    }
                    
                }
            }
        }

        private void dataGridViewUser_SelectionChanged(object sender, EventArgs e)
        {
            dataGridViewMac.DataSource = null;
            if (dataGridViewUser.CurrentCellAddress.Y > -1)
                {
                    tbUserid.DataBindings.Clear();
                    tbUserid.DataBindings.Add("Text", bindingSource, "USER_ID");
                    tbFullName.DataBindings.Clear();
                    tbFullName.DataBindings.Add("Text", bindingSource, "FULL_NAME");
                    tbLoginid.DataBindings.Clear();
                    tbLoginid.DataBindings.Add("Text", bindingSource, "USER_NAME");
                    //tbPassword.DataBindings.Clear();
                    //tbPassword.DataBindings.Add("Text", bindingSource, "USER_PASSWORD");
                    tbLimit.DataBindings.Clear();
                    tbLimit.DataBindings.Add("Text", bindingSource, "ONLINE_LIMIT");
                    dataGridViewUser.Refresh();
                }

                var eaddbContext = new EadEntitiesModel();
                IQueryable<object> mac = from m in eaddbContext.TBL_USER_IP_MAC_INFOs
                                         where m.USER_ID == Convert.ToInt32(dataGridViewUser.CurrentRow.Cells["USER_ID"].Value.ToString())
                                         orderby m.ID descending 
                                         select new { m.ID, m.USER_ID, m.MAC_ADDRESS };
            if (mac.Any())
            {
                BindingSource macBind = new BindingSource();
                macBind.DataSource = mac;
                dataGridViewMac.DataSource = macBind;

                dataGridViewMac.Columns["ID"].HeaderText = "ID";
                dataGridViewMac.Columns["USER_ID"].HeaderText = "用户ID";
                dataGridViewMac.Columns["MAC_ADDRESS"].HeaderText = "Mac地址";
                dataGridViewMac.Columns["MAC_ADDRESS"].Width = 160;
            }
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbUserid.Text))
            {
                MessageBox.Show("请先执行查询,找出用户!");
            }
            else
            {
                tbPassword.Focus();
                tbPassword.ReadOnly = false;
                tbPassword.Text = "";
                tbLimit.ReadOnly = false;
                btSave.Enabled = true;
            }
    
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbLimit.Text))
            {

                using (var dbconText = new EadEntitiesModel())
                {
                    TBL_ACM_USER user = (from u in dbconText.TBL_ACM_USERs
                                         where u.USER_ID == Convert.ToInt64(tbUserid.Text)
                                         select u).FirstOrDefault();
                    if(!string.IsNullOrEmpty(tbPassword.Text))
                        user.USER_PASSWORD = IMCPassWord.Gen(tbPassword.Text);
                    user.ONLINE_LIMIT = Convert.ToInt32(tbLimit.Text);
                    dbconText.SaveChanges();
                }

                btQuery_Click(sender, e);
                btSave.Enabled = false;
                tbPassword.ReadOnly = true;
                tbLimit.ReadOnly = true;
            }
        }

        private void tbQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                btQuery_Click(sender,e);
            }
        }

        private void tbLimit_Validating(object sender, CancelEventArgs e)
        {
            if (CheckNum())
            {
                errorProvider1.SetError(tbLimit, "");
                btSave.Enabled = true;
            }
            else
            {
                errorProvider1.SetError(tbLimit, "只允许输入1至99间的整数");
                btSave.Enabled = false;
            }
        }

        private void tbLimit_TextChanged(object sender, EventArgs e)
        {
            if (CheckNum())
                {
                    errorProvider1.SetError(tbLimit, "");
                    btSave.Enabled = true;
                }
                else
                {
                    errorProvider1.SetError(tbLimit, "只允许输入1至99间的整数");
                    btSave.Enabled = false;
                }
        }

        private bool CheckNum()
        {
            try
            {
                if (Regex.IsMatch(tbLimit.Text, @"^([1-9])(\d){0,1}$"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (ArgumentException ex)
            {
                return false;
            }
        }

        private bool CheckMAC()
        {
            try
            {
                if (Regex.IsMatch(tbMacAddress.Text, @"^([0-9a-fA-F]{2})((:|-)[0-9a-fA-F]{2}){5}$"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (ArgumentException ex)
            {
                return false;
            }
        }

        private void btInsert_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbUserid.Text))
            {
                if (CheckMAC())
                {
                    var dbConText = new EadEntitiesModel();

                    //mac地址重复判断
                    var ExistMac = (from m in dbConText.TBL_USER_IP_MAC_INFOs
                                    from u in dbConText.TBL_ACM_USERs
                                    where m.MAC_ADDRESS == tbMacAddress.Text.Replace("-", ":") && u.USER_ID == m.USER_ID
                                    select new{m,u});
                    if (ExistMac.Any())
                    {
                        string username=null;
                        string fullname=null;
                        int count = ExistMac.Count();
                        if (ExistMac.Count() > 1)
                        {
                            for (int i = 0; i <count ; i++)
                            {
                                username += ExistMac.ToList()[i].u.USER_NAME+",";
                                fullname += ExistMac.ToList()[i].u.FULL_NAME+",";
                            }
                            username = username.Substring(0, username.Length - 1);
                            fullname = fullname.Substring(0, fullname.Length - 1);
                        }
                        else
                        {
                            username += ExistMac.FirstOrDefault().u.USER_NAME;
                            fullname += ExistMac.FirstOrDefault().u.FULL_NAME;
                        }

                        MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel;
                        DialogResult result;
                        result = MessageBox.Show(this, 
                            string.Format("MAC地址'{0}'在系统中已存在{1}条记录，绑定用户为:\n{2}<{3}>。\n\n是：将已绑定MAC地址所有者更新为当前用户。仅存在一条记录时使用！\n否：删除原记录，绑定MAC至当前用户。存在多条记录时使用！",tbMacAddress.Text, count, username,fullname), 
                            "MAC地址已存在!", 
                            buttons);
                        switch (result)
                        {
                                case DialogResult.Yes:
                                {
                                    //变更所有者
                                    ExistMac.FirstOrDefault().m.USER_ID = Convert.ToInt32(tbUserid.Text);
                                    dbConText.SaveChanges();
                                }
                                break;

                                case DialogResult.No:
                                {
                                    for (int i = 0; i <count ; i++)
                                    {
                                        dbConText.Delete(ExistMac.ToList()[i].m);
                                    }
                                    dbConText.SaveChanges();
                                    //删除原记录，再插入新记录
                                    TBL_USER_IP_MAC_INFO macInfo = new TBL_USER_IP_MAC_INFO();
                                    macInfo.USER_ID = Convert.ToInt32(tbUserid.Text);
                                    macInfo.MAC_ADDRESS = tbMacAddress.Text.Replace("-", ":").ToUpper();
                                    dbConText.Add(macInfo);
                                    dbConText.SaveChanges(); 
                                }
                                break;
                                
                                case DialogResult.Cancel:
                                break;
                        }
                    }
                    else
                    {
                        TBL_USER_IP_MAC_INFO macInfo = new TBL_USER_IP_MAC_INFO();
                        macInfo.USER_ID = Convert.ToInt32(tbUserid.Text);
                        macInfo.MAC_ADDRESS = tbMacAddress.Text.Replace("-",":").ToUpper();
                        dbConText.Add(macInfo);
                        dbConText.SaveChanges();                        
                    }
                }
            }
            else
            {
                MessageBox.Show("请先查询并选择用户!");
            }
            btQuery_Click(sender, e);
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewMac.SelectedRows)
            {
                var dbConText = new EadEntitiesModel();
                TBL_USER_IP_MAC_INFO mac = (from m in dbConText.TBL_USER_IP_MAC_INFOs
                                            where m.ID == Convert.ToInt32(row.Cells["ID"].Value.ToString())
                                            select m).FirstOrDefault();
                dbConText.Delete(mac);
                dbConText.SaveChanges();
            }
            btQuery_Click(sender,e);
            
        }
 
        private void tbMacAddress_TextChanged(object sender, EventArgs e)
        {
            if (CheckMAC())
            {
                errorProvider1.SetError(tbMacAddress, "");
                btInsert.Enabled = true;
            }
            else
            {
                errorProvider1.SetError(tbMacAddress, "MAC地址格式不符合规范！必须是6段a至f和数字的组合。");
                btInsert.Enabled = false;
            }
        }

        private void tbMacAddress_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btInsert_Click(sender,e);
            }
        }
    }
}
